package com.yuzhi.master.drainMsgNotice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.helper.LoginHelper;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.master.drainMsgNotice.domain.DrainMsgNotice;
import com.yuzhi.master.drainMsgNotice.domain.bo.DrainMsgNoticeBo;
import com.yuzhi.master.drainMsgNotice.domain.request.DrainMsgNoticeReq;
import com.yuzhi.master.drainMsgNotice.domain.vo.DrainMsgNoticeVo;
import com.yuzhi.master.drainMsgNotice.mapper.DrainMsgNoticeMapper;
import com.yuzhi.master.drainMsgNotice.service.IDrainMsgNoticeService;
import com.yuzhi.master.drainMsgTemplate.domain.vo.DrainMsgTemplateVo;
import com.yuzhi.master.drainMsgTemplate.service.IDrainMsgTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 消息通知Service业务层处理
 *
 * @author coding123
 * @date 2025-08-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DrainMsgNoticeServiceImpl implements IDrainMsgNoticeService {

    private final DrainMsgNoticeMapper baseMapper;

    private final IDrainMsgTemplateService IDrainMsgTemplateService;

    /**
     * 查询消息通知
     */
    @Override
    public DrainMsgNoticeVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询消息通知列表
     */
    @Override
    public PageDataInfo<DrainMsgNoticeVo> queryPageList(DrainMsgNoticeReq request) {
        LambdaQueryWrapper<DrainMsgNotice> lqw = buildQueryWrapper(request);
        Page<DrainMsgNoticeVo> result = baseMapper.selectVoPage(request.getPageQuery().build(), lqw);
        return PageDataInfo.build(result);
    }

    /**
     * 查询消息通知列表
     */
    @Override
    public List<DrainMsgNoticeVo> queryList(DrainMsgNoticeReq request) {
        LambdaQueryWrapper<DrainMsgNotice> lqw = buildQueryWrapper(request);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrainMsgNotice> buildQueryWrapper(DrainMsgNoticeReq request) {
        Map<String, Object> params = request.getParams();
        LambdaQueryWrapper<DrainMsgNotice> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(request.getNoticeUser()), DrainMsgNotice::getNoticeUser,request.getNoticeUser());
        lqw.eq(StringUtils.isNotBlank(request.getFkType()), DrainMsgNotice::getFkType,request.getFkType());
        lqw.eq(StringUtils.isNotBlank(request.getNoticeStatus()), DrainMsgNotice::getNoticeStatus,request.getNoticeStatus());
        if(request.getStartDate()!=null && request.getEndDate()!=null)
        {
            LocalDateTime startDate = request.getStartDate().toLocalDate().atStartOfDay();
            LocalDateTime endDate = request.getEndDate().toLocalDate().atTime(LocalTime.MAX);

            lqw.between(DrainMsgNotice::getNoticeTime, startDate, endDate);

        }
        lqw.orderByDesc(DrainMsgNotice::getNoticeTime);
        return lqw;
    }

    /**
     * 新增消息通知
     */
    @Override
    public Boolean insertByBo(DrainMsgNoticeBo bo) {
        DrainMsgNotice add = BeanUtil.toBean(bo, DrainMsgNotice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改消息通知
     */
    @Override
    public Boolean updateByBo(DrainMsgNoticeBo bo) {
        DrainMsgNotice update = BeanUtil.toBean(bo, DrainMsgNotice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DrainMsgNotice entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除消息通知
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据id删除消息通知信息
     */
    @Override
    public Boolean deleteById(String id, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteById(id) > 0;
    }

    /**
     * 消息通知
     * @param noticeBo
     * @param params
     */
    @Override
    public DrainMsgNotice sendMsgNotice(DrainMsgNoticeBo  noticeBo,Map<String,String>  params)
    {
        if(noticeBo!=null && params!=null)
        {
            String msgType = noticeBo.getFkType();
            if(StringUtils.isNotBlank(msgType))
            {
                //根据消息类型  查询消息模板
                DrainMsgTemplateVo  templateVo  = IDrainMsgTemplateService.queryMsgTemplate(msgType);
                if(templateVo != null)
                {
                    String template  = templateVo.getTemplateVal();
                    // 消息参数替换
                    String  templateVal =   replaceTemplateSimple( template, params);

                    noticeBo.setNoticeVal(templateVal);
                }
                noticeBo.setNoticeTime(LocalDateTime.now());
                //设置未读
                noticeBo.setNoticeStatus("0");

                DrainMsgNotice add = BeanUtil.toBean(noticeBo, DrainMsgNotice.class);
                baseMapper.insert(add);

                return add;
            }
        }

        return null;
    }


    /**
     * 使用字符串替换
     * @param template 消息模板
     * @param params 参数Map
     * @return 替换后的消息内容
     */
    public static String replaceTemplateSimple(String template, Map<String, String> params) {
        if (template == null || template.isEmpty()) {
            return template;
        }

        String result = template;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String placeholder = "{" + entry.getKey() + "}";
            result = result.replace(placeholder, entry.getValue()==null?"":entry.getValue());
        }

        return result;
    }


    /**
     * 更新消息通知状态(0-未读  1-已读)
     */
    @Override
    public Boolean updateNoticeStatusById(String id,String status)
    {
        DrainMsgNotice  notice  = baseMapper.selectById(id);
        if(notice != null)
        {
            if(StringUtils.isNotBlank(status))
            {
                notice.setNoticeStatus(status);
            }

            return baseMapper.updateById(notice) > 0;

        }

        return false;
    }


    /**
     * 根据消息类型修改消息通知状态
     * 通知状态(0-未读  1-已读)
     * @param fkType
     * @return
     */
    @Override
    public Boolean updateStatusByFkType(String fkType,String status)
    {
        return baseMapper.update(null,
                new LambdaUpdateWrapper<DrainMsgNotice>()
                        .eq(DrainMsgNotice::getFkType, fkType)
                        .set(DrainMsgNotice::getNoticeStatus, status)) > 0;
    }


    /**
     * 移动端查询我的消息
     * 每种消息类型取最新的一条
     * @return
     */
    @Override
    public  List<DrainMsgNoticeVo>  getAppLastMsgNotice()
    {
        //获取当前登录的用户ID
        String userId = LoginHelper.getUserId();

        List<DrainMsgNoticeVo>   voList = baseMapper.getAppLastMsgNotice(userId);

        return voList;
    }


}
